package com.walle.concurrenttest.pattern.activeobject;

/**
 * @author zhangjiapeng
 * @Package com.walle.concurrenttest.pattern.activeobject
 * @Description: ${todo}
 * @date 2019/2/27 15:40
 */
public class ActivationQueue {

    private static final int MAX_METHOD_REQUEST = 100;
    private  final MethodRequest[] requestQueue;
    private int tail;
    private int head;
    private int count;

    public ActivationQueue() {
        this.requestQueue = new MethodRequest[MAX_METHOD_REQUEST];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
    }

    public synchronized void putRequest(MethodRequest request){
        while (count >= MAX_METHOD_REQUEST){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        requestQueue[tail] = request;
        tail = (tail + 1) % requestQueue.length;
        count++;
        this.notifyAll();
    }

    public synchronized MethodRequest getRequest(){
        while (count <= 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        MethodRequest request = requestQueue[head];
        head = (head + 1) % requestQueue.length;
        count--;
        this.notifyAll();
        return  request;
    }
}
